package com.example.c97s3plystartermybatis;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@ComponentScan("com.example.c97s3plystartermybatis")
@EnableTransactionManagement
// 条件(鉴权)注解
@ConditionalOnClass({DataSource.class,SqlSessionFactory.class,SqlSessionFactoryBean.class})
// 限定 IOC 容器中必须包含指定的bean
// @ConditionalOnBean
// 限定 IOC 容器中必须不能包含指定的bean
// @ConditionalOnMissingBean
// 判断环境参数
@ConditionalOnProperty("spring.datasource.url")

public class MyBatisConfig {

    @Resource
    DataSourcesConfig dsc;

    @Bean   //标准jdbc数据源: 以下是写硬代码来配置数据源的， 生产不可用
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(dsc.getDriverClassName());
        dataSource.setUrl(dsc.getUrl());
        dataSource.setUsername(dsc.getUsername());
        dataSource.setPassword(dsc.getPassword());
        return dataSource;
    }

    @Bean
    @Resource
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setConfiguration(configuration());
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public org.apache.ibatis.session.Configuration configuration() {
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLogImpl(StdOutImpl.class);
        return configuration;
    }
}
